//
//  GroupActiveDetailViewController.m
//  Findif
//
//  Created by Mac on 2019/3/7.
//  Copyright © 2019年 Cicel Chen. All rights reserved.
//

#import "GroupActiveDetailViewController.h"
#import "CreateActiveHeaderView.h"
#import "CreateGroupActiveTableViewCell.h"
#import "GrayFooterView.h"
#import "GroupActiveDetailInfoTableViewCell.h"
#import "JoinActivePeopleHeaderView.h"
//#import "ActiveInfoModel.h"
#import "SureOrderViewController.h"
#import "GroupMemberTableViewCell.h"
#import "MemberModel.h"
#import "PersonalViewController.h"
#import "MapViewController.h"
#import "FinishPersonalView.h"

@interface GroupActiveDetailViewController ()<UITableViewDataSource,UITableViewDelegate,CreateGroupActiveTableViewCellDelegate,FinishPersonalViewDelegate>

@property (nonatomic, weak)UITableView * tableView;
@property (nonatomic, strong)NSArray * array;
@property (nonatomic, strong)NSDictionary * dict;
@property (nonatomic, copy)NSString * orderID;
@property (nonatomic, strong)NSArray <MemberModel *> * buyList;

@property (nonatomic, weak)UIToolbar * finishToolbar;
@property (nonatomic, strong)FinishPersonalView * finishView;


@end

@implementation GroupActiveDetailViewController


- (void)viewWillAppear:(BOOL)animated{
    
   [self loadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.array = @[@"活动项目",@"活动时间",@"活动地址"];
    
//    self.model = [NSArray yy_modelArrayWithClass:[ActiveInfoModel class] json:self.dict[@"activity_info"]];
    
    [self setupNav];
    [self setupUI];
    
}

- (void)loadData{
    
    [[ZRNetworkTool sharedTool] getGroupActivityGoodsInfoWithID:self.ID WithBlock:^(BOOL success, id responseData) {
        
//        NSLog(@"res===%@",responseData);
        if (success) {
            
           self.dict = responseData[@"data"];
            self.buyList = [NSArray yy_modelArrayWithClass:[MemberModel class] json:self.dict[@"buy_user"]];
        }
        
    }];
}


- (void)setDict:(NSDictionary *)dict{
//    modelWithDictionary:(NSDictionary *)dictionary
    _dict = dict;
    self.model = [GroupActiveModel yy_modelWithDictionary:dict];
    
    [self.tableView reloadData];
}


- (void)setBuyList:(NSArray<MemberModel *> *)buyList{
    
    _buyList = buyList;
    
    [self.tableView reloadData];
}


- (void)setupNav{
    
    self.title = @"活动";
    
    UIButton * rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 35 * SCREENH6, 15 * SCREENH6)];
    
    [rightButton setTitle:@"取消" forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(didCancelButton) forControlEvents:UIControlEventTouchUpInside];
    [rightButton setTitleColor:ZRBlackColor forState:UIControlStateNormal];
    rightButton.titleLabel.font = [UIFont systemFontOfSize:15 * SCREENH6];
    if ([self.identity isEqualToString:@"1"]) {
        
        rightButton.hidden = NO;
    }else{
        
        rightButton.hidden = YES;
    }
    
    UIBarButtonItem * rightBar = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    
    self.navigationItem.rightBarButtonItem = rightBar;
}


- (void)setupUI{
    
    self.view.backgroundColor = ColorWithRGB(0xF0F0F0);
    
    UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH) style:UITableViewStyleGrouped];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = ColorWithRGB(0xF0F0F0);
    //    tableView.rowHeight = 50 * SCREENH6;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.showsVerticalScrollIndicator = NO;
    
    self.tableView = tableView;
    
    [self.tableView registerClass:[CreateGroupActiveTableViewCell class] forCellReuseIdentifier:@"GroupActiveDetailTableViewCell"];
    [self.tableView registerClass:[CreateActiveHeaderView class] forHeaderFooterViewReuseIdentifier:@"ActiveDetailHeaderView"];
    [self.tableView registerClass:[GroupActiveDetailInfoTableViewCell class] forCellReuseIdentifier:@"GroupActiveDetailInfoTableViewCell"];
    [self.tableView registerClass:[GrayFooterView class] forHeaderFooterViewReuseIdentifier:@"ActiveDetailGrayFooterView"];
    [self.tableView registerClass:[JoinActivePeopleHeaderView class] forHeaderFooterViewReuseIdentifier:@"JoinActivePeopleHeaderView"];
    [self.tableView registerClass:[GroupMemberTableViewCell class] forCellReuseIdentifier:@"BuyPeopleTableViewCell"];
    
    //    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
    //
    //        [self loadData];
    //    }];
    
    [self.view addSubview:self.tableView];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 3;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 0) {
        
        return 4;
    }else if (section == 1){
        
        return 1;
    }else{
        
        return self.buyList.count;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
        CreateGroupActiveTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GroupActiveDetailTableViewCell" forIndexPath:indexPath];
        cell.delegate = self;
        
        if (indexPath.row == 0) {

            cell.textFiled.hidden = YES;
            cell.joinButton.hidden = NO;
            cell.subLabel.hidden = YES;
            cell.titleLabel.hidden = NO;
            
//            cell.titleLabel.text = self.model.activity_title;
            cell.titleLabel.text = self.dict[@"activity_title"];
            int is_join = [self.dict[@"is_join"] intValue];
            if (is_join == 0) {
                
                cell.joinButton.selected = NO;
            }else{
                
               cell.joinButton.selected = YES;
                cell.joinButton.userInteractionEnabled = NO;
            }
        }else{
            
            cell.textFiled.hidden = YES;
            cell.joinButton.hidden = YES;
            cell.titleLabel.hidden = NO;
            cell.subLabel.hidden = NO;
            
            cell.titleLabel.text = self.array[indexPath.row - 1];
            if (indexPath.row == 1) {
                
//                cell.subLabel.text = self.model.merchants_goods_name;
                cell.subLabel.text = self.dict[@"merchants_goods_name"];
            }else if (indexPath.row == 2){
                
//                cell.subLabel.text = self.model.activity_time;
               cell.subLabel.text =  self.dict[@"activity_time"];
            }else if (indexPath.row == 3){
                
//                cell.subLabel.text = self.model.merchants_address;
                cell.subLabel.text =  self.dict[@"merchants_address"];
                cell.subLabel.textColor = ColorWithRGB(0x4C87D8);
                cell.subLabel.userInteractionEnabled = YES;
                UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
                [cell.subLabel addGestureRecognizer:tapGR];
            }
        }
        
        return cell;
    }else if (indexPath.section == 1){
        
        GroupActiveDetailInfoTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"GroupActiveDetailInfoTableViewCell" forIndexPath:indexPath];
        
         cell.model = self.model;

        return cell;
    }else{
        
        GroupMemberTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"BuyPeopleTableViewCell" forIndexPath:indexPath];

        cell.memberModel = self.buyList[indexPath.row];
        return cell;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        
        return 200 * SCREENH6;
    }else if (section == 1){
        
        return 0;
    }else{
        
        return 45 * SCREENH6;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 10 * SCREENH6;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    if (section == 0) {
        
        CreateActiveHeaderView * header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"ActiveDetailHeaderView"];
        
//        header.model = self.model;
        header.dict = self.dict;
        
        return header;
    }else if (section == 2){
        
        JoinActivePeopleHeaderView * header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"JoinActivePeopleHeaderView"];
        
        header.countLabel.text = [NSString stringWithFormat:@"%ld人",self.buyList.count];
        return header;
    }else{
        
        return nil;
    }
    
}


- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    GrayFooterView * header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"ActiveDetailGrayFooterView"];
    
    return header;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
        return 50 * SCREENH6;
    }else if (indexPath.section == 1){
        
//        if (self.model) {
//
            return self.model.rowHeight;
//        }else{
//
//            return 300 * SCREENH6;
//        }
//        CGFloat height = [self.dict[@"height"] floatValue];
//        return height;
    }else{
        
        return 50 * SCREENH6;
    }
}


- (void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section{
    
    
    if ([view isKindOfClass:[UITableViewHeaderFooterView class]]) {
        ((UITableViewHeaderFooterView *)view).backgroundView.backgroundColor = ColorWithRGB(0xF0F0F0);
    }
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section NS_AVAILABLE_IOS(6_0){
    
    if(section == 2){
        
        if ([view isKindOfClass:[UITableViewHeaderFooterView class]]) {
            ((UITableViewHeaderFooterView *)view).backgroundView.backgroundColor = ColorWithRGB(0xF0F0F0);
        }
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 2) {
        
        MemberModel * model = self.buyList[indexPath.row];
        
        HiddenBar;
        
        NSString * ID = [NSString stringWithFormat:@"%@",model.goods_order_user_id];
        NSString * user_id = DEF_GET_OBJECT(@"id");
        if ([user_id isEqualToString:ID]) {
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:@"亲，不能点击自己哦"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }else{
            
            PersonalViewController * personVC = [PersonalViewController new];
            
            personVC.ID = ID;
            
            [self.navigationController pushViewController:personVC animated:YES];
        }
        
    }
}


- (void)clickJoinButton{
    
    int merchants_goods_is_need_insurance = [self.dict[@"merchants_goods_is_need_insurance"] intValue];
    
    if (merchants_goods_is_need_insurance == 0) {
        
        [self clickNextButton];
    }else if(merchants_goods_is_need_insurance == 1){
        
        UIToolbar *toolbar = [[UIToolbar alloc]initWithFrame:[UIScreen mainScreen].bounds];
        //样式
        toolbar.barStyle = UIBarStyleBlackTranslucent;//半透明
        //透明度
        toolbar.alpha = 0.5f;
        
        self.finishToolbar = toolbar;
        
        [self.tabBarController.view addSubview:self.finishToolbar];
        
        self.finishView = [[FinishPersonalView alloc] initWithFrame:CGRectMake(15 * SCREENH6, 0, 345 * SCREENH6, 275 * SCREENH6)];
        
        self.finishView.backgroundColor = ZRWhiteColor;
        self.finishView.layer.cornerRadius = 5 * SCREENH6;
        self.finishView.layer.masksToBounds = YES;
        self.finishView.delegate = self;
        
        self.finishView.centerY = self.view.centerY;
        
        [self.tabBarController.view addSubview:self.finishView];
    }
    
   
}


- (void)pushToSureVC{
    
    HiddenBar;
    SureOrderViewController * sureVC = [SureOrderViewController new];
    sureVC.orderID = self.orderID;
    sureVC.dict = self.dict;
    sureVC.time = self.dict[@"activity_time"];
    sureVC.type = @"1";
    
    [self.navigationController pushViewController:sureVC animated:YES];
}

- (void)didCancelButton{
    
    [[ZRNetworkTool sharedTool] deleteGroupActivityGoodsWithID:self.ID WithBlock:^(BOOL success, id responseData) {
        
        if (success) {
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:responseData[@"message"]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      [self.navigationController popViewControllerAnimated:YES];
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];

        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:responseData[@"message"]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];

        }
    }];
}


- (void)tapAction{
    
    HiddenBar;
    
    MapViewController * mapVC = [MapViewController new];
    
    mapVC.merchants_latitude = [NSString stringWithFormat:@"%@",self.dict[@"merchants_latitude"]];
    mapVC.merchants_longitude = [NSString stringWithFormat:@"%@",self.dict[@"merchants_longitude"]];
    mapVC.merchants_name = self.dict[@"merchants_name"];
    mapVC.merchants_local = self.dict[@"merchants_address"];
    
    [self.navigationController pushViewController:mapVC animated:YES];
}

- (void)clickButtonWithType:(NSString *)type WithDict:(NSDictionary *)dict{
    
    if ([type isEqualToString:@"sure"]) {
        
        if ([self.finishView.ID isEqualToString:@"yes"]) {
            
            [self.finishView removeFromSuperview];
            [self.finishToolbar removeFromSuperview];
            
            [self clickNextButton];
        }else{
            
            [[ZRNetworkTool sharedTool] updateUserInfoAllWithDict:dict WithBlock:^(BOOL success, id responseData) {
                
                if (success) {
                    
                    [self clickNextButton];
                    
                    [self.finishView removeFromSuperview];
                    [self.finishToolbar removeFromSuperview];
                }else{
                    
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                   message:responseData[@"message"]
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                          handler:^(UIAlertAction * action) {
                                                                              
                                                                          }];
                    
                    [alert addAction:defaultAction];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            }];
        }
        
    }else{
        
        [self.finishView removeFromSuperview];
        [self.finishToolbar removeFromSuperview];
    }
    
    
    
}

- (void)firstFinishPersonalInfo{
    
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                   message:@"请先完善个人信息"
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                          handler:^(UIAlertAction * action) {
                                                              
                                                          }];
    
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
}


- (void)clickNextButton{
    
    NSString * goods_id = [NSString stringWithFormat:@"%@",self.dict[@"goods_id"]];
    NSString * active_id = [NSString stringWithFormat:@"%@",self.dict[@"id"]];
    NSDictionary * dict = @{@"goods_order_goods_id":goods_id,@"goods_order_goods_field":self.dict[@"activity_time"],@"goods_order_group_activity_id":active_id};
    
    [[ZRNetworkTool sharedTool] buyMerchantsGoodsWithDict:dict WithBlock:^(BOOL success, id responseData) {
        
        //        NSLog(@"res===%@",responseData);
        
        if (success) {
            
            NSDictionary * dict = responseData[@"data"];
            self.orderID = [NSString stringWithFormat:@"%@",dict[@"id"]];
            [self pushToSureVC];
        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:responseData[@"message"]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }];
}

@end
